<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Team;
use App\Models\TeamP;
use EasyWeChat\Core\Exception;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\News;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\Validator;

class ActiveController extends Controller
{
    protected $wechat = null;

    public function __construct()
    {
        $wechatConfig = config('wechat');
        $app = new Application($wechatConfig);
        $openPlatform = $app->open_platform;
        $authorizationInfo = \DB::table("open_platform")->where('app','wx2b4fa3fce5bef950')->first();
        $wechatApp = $openPlatform->createAuthorizerApplication($authorizationInfo->app_id , $authorizationInfo->refresh_token);

        $this->wechat = $wechatApp;
    }

    //获取所有产品
    public function products()
    {
        $pro_list = Product::all();
        if($pro_list){
            return response()->json(['code'=>1, 'mgs'=>'', 'data'=>$pro_list]);
        }else{
            return response()->json(['code'=>0, 'mgs'=>'没有数据~', 'data'=>'']);
        }
    }

    //获取产品
    /**
     *   method: post
     *   post: [
     *      'team_id' : 团队id
     *   ]
     */
    public function product(Request $request)
    {
        if($request->has('team_id')){
            global $g_uuuid;
            global $g_openid;

            $return_data = [];
            $team = Team::find($request->input('team_id'));

            $teamPmodel = new TeamP();
            $teamMember = $teamPmodel->getTeamPMyTeamId($request->get('team_id'));

            $team->member = $teamMember;
            $return_data['team'] = $team;

            /**
             * 判断是否是我的团
             */
            //如果这个团本来就是我的
            $return_data['is_my'] = $team->openid == $g_openid ? 1:0;
            //如果我已经是这个团的成员了
            if(!$return_data['is_my']) {
                foreach ($team->member as $tm) {
                    if ($tm->tm_openid == $g_openid) {
                        $return_data['is_my'] = 1;
                    }
                }
            }


            $pro_info = Product::where('id',$team['pro_id'])->first();
            $pro_info->datemax_format = date('Y/m/d H:i:s',strtotime($pro_info->datemax));
            $return_data['pro_info'] = $pro_info;

            $teamModel = new Team();
            $return_data['myTeam'] = $teamModel->getMyTeamByProId($team['pro_id'] , $g_uuuid);

            return response()->json(['code'=>1, 'msg'=>'', 'data'=>$return_data]);
        }else{
            return response()->json(['code'=>0, 'msg'=>'没有数据~', 'data'=>'']);
        }

    }

    //是否组团
    /**
     *   method: post
     *   post: [
     *      'pro_id' : 产品id
     *      'openid' : 用户id,
     *      'invent' : 邀请 团队组的id
     *   ]
     */
    public function joinTeam(Request $request)
    {
        global $g_openid;
        global $g_nickname;

        // 兼容传team_id
        if($request->has('team_id')){
            $team_info = Team::find($request->input('team_id'));
            if(!$team_info){
                return response()->json(['code'=>0, 'msg'=>'没有这个团']);
            }
        }else{
            return response()->json(['code'=>0, 'msg'=>'非法请求']);
        }
        $input = [
            'pro_id' => isset($team_info['pro_id']) ? $team_info['pro_id'] : $request->input('pro_id'),
            'invent' => isset($team_info['id']) ? $team_info['id'] : $request->input('invent',''),
            'openid' => $g_openid
        ];

        //判断活动是否过期了
        $pro_info = Product::find($input['pro_id']);
        if(time() > strtotime($pro_info->datemax)){
            return response()->json(['code'=>0, 'msg'=>'活动已过期']);
        }

        //判断是否自己入自己团
        $team_p_info = Team::find($input['invent'])->teamP()->get();
        $team_p_info_openid = [];
        foreach ($team_p_info as $k=>$v){
            $team_p_info_openid[] = $v['tm_openid'];
        }
        if(in_array($input['openid'],$team_p_info_openid)){

            if(Team::where('nums' , '<' , '3')->where('openid' , $g_openid)->first()){
                return response()->json(['code'=>0, 'msg'=>'您还有团没有满员，找好友参团，点击右上角，你懂的']);
            }else{
                $this->creatTeam($input['openid'] , $input['pro_id']);
            }
        }

        if($input['invent']){
            //判断是否参加team,该组是否满了])
            $count = Team::find($input['invent'])->teamP()->count();

            //判断用户是否在其他组了
            $pro_team_p = [];
            $tm_info = DB::table('team as t')
                ->select('tp.*')
                ->leftjoin('team_p as tp','tp.tm_id','t.id')
                ->where('t.pro_id',$input['pro_id'])
                ->where('tp.is_t',0)
                ->get();
            foreach ($tm_info as $k=>$v){
                $pro_team_p[] = $v->tm_openid;
            }
            //$tm_info = TeamP::where('tm_openid',$input['openid'])
              //  ->where('is_t',0)->first();
            if(in_array($input['openid'],$pro_team_p)){
                $istInfo = DB::table('team_p as p')
                    ->select('m.nickname' , 'p.tm_id')
                    ->leftjoin('member as m' , 'm.openid' , '=' , 'p.tm_openid')
                    ->leftjoin('team as t','p.tm_id','t.id')
                    ->where('p.is_t' , 1)
                    ->where('p.tm_openid' , $input['openid'])
                    ->where('t.pro_id',$input['pro_id'])
                    ->first();
                if($istInfo){
                    return response()->json(['code'=>2, 'msg'=>"每个人只能参加一个他人创建的团，你之前已加入{$istInfo->nickname}的团了" , 'team_id' => $istInfo->tm_id ]);
                }else{
                    return response()->json(['code'=>2, 'msg'=>'每个人只能参加一个他人创建的团，你之前已加入其他人的团了' , 'team_id' => '' ]);
                }
            }

            if($count < 3){
                //说明有组
                $input_p = [
                    'tm_openid' => $input['openid'],
                    'tm_id' => $input['invent'],    //团长所属开组的id
                    'is_t' => 0   //是否是团长
                ];
                $res = TeamP::create($input_p);
                if($res){
                    //每次加入维护nums
                    DB::table('team')->where('id',$input['invent'])->increment('nums', 1);
                
                    //判断是否是3个
                    $count = Team::find($input['invent'])->teamP()->count();
                    if($count == 3){
                        //更新下完成状态
                        Team::where('id',$input['invent'])->update(['status' =>1 ]);
                    }
                    $pro_img = Product::find($team_info['pro_id'])->pluck('pro_img');
                    //发送微信消息
                    $wx_data = [
                        'title' => '新团员加入消息~~',
                        'description' => '恭喜您有新团员 '.$g_nickname.' 加入成功啦!',
                        'image' => env('API_HOST','http://wechat.zaizaihui.cn')."/uploads/".$pro_img,
                        'url' => env('WEB_HOST')."/index?team_id=".$input['invent'],
                    ];
                    $this->sendTplMsg($team_info['openid'],$wx_data);
                    //发送微信消息
                    $wx_data = [
                        'title' => '新加入团消息~~',
                        'description' => '恭喜您新加入团成功啦!',
                        'image' => env('API_HOST','http://wechat.zaizaihui.cn')."/uploads/".$pro_img,
                        'url' => env('WEB_HOST')."/index?team_id=".$input['invent'],
                    ];
                    $this->sendTplMsg($g_openid,$wx_data);
                    return response()->json(['code'=>1, 'msg'=> '加入团成功']);
                }else{
                    return response()->json(['code'=>0, 'msg'=>'加入团失败']);
                }
            }else{
                $this->creatTeam($input['openid'] , $input['pro_id']);
            }
        }

    }

    public function creatTeam($openid , $proId){
        //判断是否开团已经有10个了
        $team_has = Team::where('openid',$openid)
            ->where('pro_id' , $proId)
            ->count();
        if($team_has == 10){
            return response()->json(['code'=>0, 'msg'=> '已达到开团最大值' ]);
        }

        //判断是否有新开团
        $counts = Team::where('openid',$openid)
            ->where('pro_id' , $proId)
            ->where('status',0)->count();
        if(!$counts < 1){
            return response()->json(['code'=>0, 'msg'=> '已有新团,并且暂时没有满员,不能重新开团~' ]);
        }

        //创建新团
        $input_tm = [
            'openid' => $openid,
            'nums' => '1',
            'pro_id' => $proId,
            'status' => 0
        ];
        $res = Team::create($input_tm);
        $input_tmp = [
            'tm_openid' => $openid,
            'tm_id' => $res->id,
            'is_t' => 1,
        ];
        $resp = TeamP::create($input_tmp);
        if($res && $resp){
            //发送微信消息
            $pro_img = Product::find($proId)->pluck('pro_img');
            $wx_data = [
                'title' => '新开团消息~~',
                'description' => '恭喜您新开团成功啦!',
                'image' => env('API_HOST','http://wechat.zaizaihui.cn')."/uploads/".$pro_img,
                'url' => env('WEB_HOST')."/index?team_id=".$res->id,
            ];
            $this->sendTplMsg($openid,$wx_data);
            return response()->json(['code'=>1, 'msg'=> '开团成功' ]);
        }else{
            return response()->json(['code'=>0, 'msg'=> '开团失败']);
        }
    }

    //发送客服消息
    protected function sendTplMsg($openid , $data = [])
    {
        $staff = $this->wechat->staff;
        //发送图文消息
        //title 标题
        //description 描述
        //image 图片链接
        //url 链接 URL

        $news = new News($data);

        try{
            $staff->message($news)->to($openid)->send();
        }catch (Exception $e){

        }
    }

    //获取我的team
    /**
     *      method : post
     *      team_id   :  team_id
     *
     */
    public function getTeam(Request $request)
    {
        //获取用户的team_id 拿到所有团员
        if($request->has('team_id')){
            $temam_info = Team::find($request->input('team_id'))->teamP()->leftJoin('member','tm_openid','=','openid')->get();
            return response()->json(['code'=>1, 'msg'=>'', 'data'=>$temam_info]);
        }else{
            return response()->json(['code'=>0, 'msg'=>'没有数据', 'data'=>'']);
        }
    }

    /*
     * 获取我所有的某个商品所有的团
     */
    public function getMyTeamByProId($proId , Request $request){

        $uid = 1;

        $teamModel = new Team();
        $myTeam = $teamModel->getMyTeamByProId($proId , $uid);

        return response()->json(['code'=>1, 'msg'=>'', 'data'=>$myTeam]);
    }


    //获取微信js sdk
    /**
     *   [
     *      mehod : 'post',
     *      request_params : [
     *          'apis' : str,
     *          'debug' : true/false   //是否开启调试
     *      ]
     *      response : [
     *          'code' => 'xx'  1success  0 error
     *          'msg'  =>  '消息提示'
     *          'data' => xxx     返回数据
     *      ]
     *   ]
     */
    //参数1, api参数  2,是否开启调试 3不知道, 4是否返回json格式
    public function getJsSdk(Request $request)
    {
        $apis = $request->input('apis');
        if($apis){
            $apis_arr = explode(',',$apis);
        }else{
            $apis_arr = ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo'];
        }

        $wechatConfig = config('wechat');
        $app = new Application($wechatConfig);
        $openPlatform = $app->open_platform;
        $authorizationInfo = \DB::table("open_platform")->where('app','wx2b4fa3fce5bef950')->first();

        $wechatApp = $openPlatform->createAuthorizerApplication($authorizationInfo->app_id , $authorizationInfo->refresh_token);

        $js = $wechatApp->js;

        $debug = false;
        if($request->has('debug')){
            $debug = $request->input('debug');
        }

        if($request->has('url')) {
            $js->setUrl($request->get('url'));
        }

        $config = $js->config($apis_arr, $debug, $beta = false, $json = true);
        if(!empty($config)){
            return response()->json(['code'=>1, 'msg'=>'', 'data'=>$config]);
        }else{
            return response()->json(['code'=>0, 'msg'=>'没有数据~', 'data'=>'']);
        }
    }


    /**
     *  获取中奖名单
     *   [
     *      mehod : 'post',
     *      request_params : [
     *          pro_id : 产品id
     *      ]
     *      response : [
     *          'code' => 'xx'  1success  0 error
     *          'msg'  =>  '消息提示'
     *          'data' =>  [
     *              tema = array(
                        ...
     *                  'team_p' => array(
                            ...
     *                  )
     *              )
     *           ]
     *      ]
     *   ]
     */
    public function getReward(Request $request)
    {
        if($request->has('pro_id')){
            $team = Team::where('status',1)->where('pro_id',$request->input('pro_id'))->get();
        }else{
            return response()->json(['code'=>0, 'msg'=>'参数错误', 'data'=>[]]);
        }
        $team_ids = [];   //所有中间的team团
        foreach ($team as $k=>$v){
            $team_ids[] = $v->id;
        }
        $tmp = DB::table('member as m')
            ->select(
                'm.openid',
                'm.nickname',
                'm.avatar',
                'm.id'
            )
            ->leftJoin('team_p as t','t.tm_openid','m.openid')
            ->whereIn('t.tm_id',$team_ids)
            ->groupBy('t.tm_openid')
            ->get();

        $proInfo = Product::where('id' , $request->input('pro_id'))->first();

        return response()->json(['code'=>1, 'msg'=>'', 'data'=>['member' => $tmp , 'product' => $proInfo]] );
    }



    public function test()
    {
//        $tmp = DB::table('team_p as tp')->select(DB::raw('m.openid,tp.tm_openid'))->leftjoin('member as m','tm_openid','openid')->get();
        //如果活动多有问题
        $pro_team_p = [];
        $tm_info = DB::table('team as t')
            ->select('tp.*')
            ->leftjoin('team_p as tp','tp.tm_id','t.id')
            ->where('t.pro_id',2)
            ->where('tp.is_t',0)
            ->get();
        foreach ($tm_info as $k=>$v){
            $pro_team_p[] = $v->tm_openid;
        }

        dd($pro_team_p);

    }

}
